<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    style="top:20px;height: 95%;">
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('button.cancel') }}</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">
        {{ $t('button.saveAndCheck') }}
      </a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">{{ $t('button.save') }}</a-button>
      <!--发起多级审核-->
      <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">{{ $t('button.startProcess') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.customer')">
              <a-select :placeholder="$t('placeholder.pleaseSelectCustomer')"
                        v-decorator="[ 'organId', validatorRules.organId ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children"
                        @change="onChangeOrgan">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addCustomer">
                    <a-icon type="plus" />
                    {{ $t('button.addCustomer') }}
                  </div>
                </div>
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billNumber')">
              <a-input :placeholder="$t('placeholder.pleaseInputBillNumber')" v-decorator.trim="[ 'billNo' ]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.salesMan')">
              <a-select :placeholder="$t('placeholder.pleaseSelectSalesMan')" v-decorator="[ 'handsPersonId' ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addPerson">
                    <a-icon type="plus" />
                    {{ $t('button.addHandlePerson') }}
                  </div>
                </div>
                <a-select-option v-for="(item,index) in personList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.receiptNo')">
              <a-input v-decorator.trim="[ 'receiptNo' ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="12" :sm="24">
            <!-- 操作按钮 -->
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="handleClickAdd">{{ $t('button.selectBill') }}</a-button>
              <span class="gap"></span>
              <a-button type="primary" icon="plus" @click="selectBeginNeed('客户')">{{ $t('button.selectBeginNeed') }}
              </a-button>
              <span class="gap"></span>
              <a-button icon="minus" @click="handleClear">{{ $t('dynamic.clear') }}</a-button>
            </div>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24">
            <j-editable-table
              :ref="refKeys[0]"
              :loading="accountTable.loading"
              :columns="accountTable.columns"
              :dataSource="accountTable.dataSource"
              :minWidth="minWidth"
              :maxHeight="300"
              :rowNumber="true"
              :rowSelection="false"
              :actionButton="false"
              @valueChange="onValueChange" />
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="2" :placeholder="$t('placeholder.pleaseInputRemark')" v-decorator="[ 'remark' ]"
                          style="margin-top:8px;" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.accountName')">
              <a-select :placeholder="$t('placeholder.pleaseSelectAccountName')"
                        v-decorator="[ 'accountId', validatorRules.accountId ]"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addAccount">
                    <a-icon type="plus" />
                    {{ $t('button.addAccount') }}
                  </div>
                </div>
                <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.totalPrice')">
              <a-input :placeholder="$t('placeholder.pleaseInputTotalReceipt')" v-decorator.trim="[ 'totalPrice' ]"
                       :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.discountMoney2')">
              <a-input :placeholder="$t('placeholder.pleaseInputDiscountMoney1')"
                       v-decorator.trim="[ 'discountMoney', validatorRules.discountMoney ]"
                       @change="onChangeDiscountMoney" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.actualReceipt')">
              <a-input :placeholder="$t('placeholder.pleaseInputActualReceipt')" v-decorator.trim="[ 'changeAmount' ]"
                       :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.payType1')">
              <a-radio-group @change="onPayTypeChange" buttonStyle="solid" v-decorator="['payType', {
                initialValue: model.payType || 1,
                 rules: [{ required: true, message: $t('placeholder.pleaseSelectPayType') }]
                }]">
                <a-radio-button :value="1">{{ $t('message.actualReceipt') }}</a-radio-button>
                <a-radio-button :value="2">{{ $t('message.chequeNumber') }}</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.chequeNumber')"
                         v-if="showChequeNumber">
              <div class="cheque-input-container">
                <a-input-search
                  v-decorator="['chequeNumber']"
                  :placeholder="$t('placeholder.pleaseSelectCheque')"
                  @search="onSearchCheque"
                  enterButton
                />
              </div>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-tag
              color="blue"
              v-if="showChequeNumber"
              v-for="cheque in selectedCheques"
              :key="cheque.chequeNumber"
              closable
              @close="removeCheque(cheque)"
            >
              {{ cheque.chequeNumber }} ({{ getChequeStatus(cheque.status) }})
            </a-tag>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billAttachment')">
              <j-upload v-model="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <debt-bill-list ref="debtBillList" @ok="debtBillListOk"></debt-bill-list>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <cheque-select-list ref="chequeSelectList" @ok="onChequeSelected"></cheque-select-list>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import DebtBillList from '../dialog/DebtBillList'
import CustomerModal from '../../system/modules/CustomerModal'
import AccountModal from '../../system/modules/AccountModal'
import PersonModal from '../../system/modules/PersonModal'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import {FormTypes} from '@/utils/JEditableTableUtil'
import {JEditableTableMixin} from '@/mixins/JEditableTableMixin'
import {FinancialModalMixin} from '../mixins/FinancialModalMixin'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import ChequeSelectList from '@views/financial/dialog/ChequeSelectList.vue'
import {getChequeByNums} from '@/api/api'

export default {
  name: 'MoneyInModal',
  mixins: [JEditableTableMixin, FinancialModalMixin],
  components: {
    DebtBillList,
    ChequeSelectList,
    CustomerModal,
    AccountModal,
    PersonModal,
    WorkflowIframe,
    JUpload,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  data() {
    return {
      title: this.$t('dynamic.operation'),
      width: '1600px',
      // 新增选中支票数组
      selectedCheques: [],
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 0,
      visible: false,
      prefixNo: 'R',
      model: {},
      fileList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      showChequeNumber: false,
      refKeys: ['accountDataTable'],
      activeKey: 'accountDataTable',
      accountTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: this.$t('search.salesBillNumber'),
            key: 'billNumber',
            width: '20%',
            type: FormTypes.input,
            readonly: true
          },
          {
            title: this.$t('search.needDebt1'),
            key: 'needDebt',
            width: '10%',
            type: FormTypes.inputNumber,
            statistics: true,
            readonly: true
          },
          {
            title: this.$t('search.finishDebt'),
            key: 'finishDebt',
            width: '10%',
            type: FormTypes.inputNumber,
            statistics: true,
            readonly: true
          },
          {
            title: this.$t('search.changeAmount2'),
            key: 'eachAmount',
            width: '10%',
            type: FormTypes.inputNumber,
            statistics: true,

            validateRules: [{ required: true, message: '本次收款不能为空' }]
          },
          { title: this.$t('search.remark'), key: 'remark', width: '20%', type: FormTypes.input }
        ]
      },
      confirmLoading: false,
      validatorRules: {
        organId: {
          rules: [{ required: true, message: this.$t('message.pleaseSelectCustomer') }]
        },
        billTime: {
          rules: [{ required: true, message: this.$t('placeholder.pleaseSelectBillDate') }]
        },
        accountId: {
          rules: [{ required: true, message: this.$t('message.pleaseSelectAccount') }]
        },
        discountMoney: {
          rules: [{ required: true, message: this.$t('placeholder.pleaseInputDiscountMoney1') }]
        }
      },
      url: {
        add: '/accountHead/addAccountHeadAndDetail',
        edit: '/accountHead/updateAccountHeadAndDetail',
        detailList: '/accountItem/getDetailList'
      }
    }
  },
  created() {
  },
  methods: {
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
        this.showChequeNumber = false
        this.selectedCheques = []
      } else {
        this.showChequeNumber = this.model.payType === 2
        this.model.billTime = this.model.billTimeStr
        console.log(this.model.payType)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'handsPersonId', 'billTime', 'billNo', 'receiptNo', 'remark',
            'accountId', 'totalPrice', 'discountMoney', 'changeAmount', 'payType', 'chequeNumber'))
        })
        this.fileList = this.model.fileName
        // 加载子表数据
        let params = {
          headerId: this.model.id
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList
        this.requestSubTableData(url, params, this.accountTable)
      }
      // 如果是支票付款方式且有支票号,查询支票详情
      if (this.model.payType === 2 && this.model.chequeNumber) {
        //const chequeNumbers = this.model.chequeNumber.split(',')
        getChequeByNums({ 'chequeNumber': this.model.chequeNumber }).then((res) => {
          if (res && res.code === 200) {
            this.selectedCheques = res.data
          }
        }).catch(err => {
          console.error('获取支票详情失败:', err)
        })
      }

      this.initSystemConfig()
      this.initCustomer()
      this.initSalesman()
      // this.initCurFinancialPerson()
      this.init
      this.initAccount()
    },
    //提交单据时整理成formData
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      billMain.type = '收款'
      for (let item of detailArr) {
        totalPrice += item.eachAmount - 0
      }
      billMain.totalPrice = totalPrice
      if (this.fileList && this.fileList.length > 0) {
        billMain.fileName = this.fileList
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.status = this.billStatus
      return {
        info: JSON.stringify(billMain),
        rows: JSON.stringify(detailArr)
      }
    },
    handleClickAdd() {
      let organId = this.form.getFieldValue('organId')
      if (organId) {
        this.$refs.debtBillList.show(organId, '出库', '销售', '客户', '')
        this.$refs.debtBillList.title = this.$t('title.selectSalesDebtBill')
      } else {
        this.$message.warning(this.$t('placeholder.pleaseSelectCustomer'))
      }
    },
    handleClear() {
      this.accountTable.dataSource = []
      this.selectedCheques = []
    },
    onSearchCheque() {
      this.$refs.chequeSelectList.show()
    },
    onChequeSelected(cheques) {
      this.selectedCheques = cheques
      this.form.setFieldsValue({
        chequeNumber: cheques.map(c => c.chequeNumber).join(',')
      })
    },
    // 移除支票
    removeCheque(cheque) {
      this.selectedCheques = this.selectedCheques.filter(item => item.chequeNumber !== cheque.chequeNumber)
      this.form.setFieldsValue({
        chequeNumber: this.selectedCheques.map(c => c.chequeNumber).join(',')
      })
    },

    // 支票状态显示
    getChequeStatus(status) {
      const statusMap = {
        0: this.$t('status.unRealized'),
        1: this.$t('status.realized'),
        2: this.$t('status.checqueReturn'),
        3: this.$t('status.returnToCustomer')
      }
      return statusMap[status] || status
    },
    onPayTypeChange(e) {
      this.showChequeNumber = e.target.value === 2
    },
    handleOk() {
      // 验证支票号
      const payType = this.form.getFieldValue('payType')
      if (payType === 2) {
        const chequeNumber = this.form.getFieldValue('chequeNumber')
        if (!chequeNumber) {
          this.$message.warning(this.$t('message.pleaseSelectCheque'))
          return
        }
      }
      // 调用父类的 handleOk 方法
      JEditableTableMixin.methods.handleOk.call(this)
    }
  }
}
</script>
<style scoped>
.action-button {
  margin-bottom: 8px;
}

.gap {
  padding-left: 8px;
}

.cheque-input-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.cheque-input {
  width: 200px; /* 或其他合适的宽度 */
}

.cheque-tag {
  margin-bottom: 0;
  white-space: nowrap;
}
</style>